package com.sunni.dao_old.impl;

import com.sunni.dao_old.UserDao;
import com.sunni.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

@Component("userDao")
public class UserDaoImpl implements UserDao {

    @Autowired
    @Qualifier("jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<User> selectAll() {
        return jdbcTemplate.query("SELECT * from sys_user", new BeanPropertyRowMapper<User>(User.class) );
    }

    /**
     * day06-16 : 添加用户数据  ，往sys_user表
     * @param user 用户信息
     * @return 返回新增user的id （数据库自动生成的）（然后往sys_user_role里插入 这里返回的userId roleId）
     */
    @Override
    public Long addUser(final User user) {
        // update重载方法 (PreparedStatementCreator,GeneratedKeyHolder)

        // 参数1： PreparedStatementCreator
        PreparedStatementCreator creator = new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement preparedStatement = connection.prepareStatement("insert into sys_user values(?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
                preparedStatement.setObject(1,null);
                preparedStatement.setString(2,user.getUsername());
                preparedStatement.setString(3,user.getEmail());
                preparedStatement.setString(4,user.getPassword());
                preparedStatement.setString(5,user.getPhoneNum());
                return preparedStatement;
            }
        };
        // 参数2：GeneratedKeyHolder
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();

        // 执行添加语句
        jdbcTemplate.update(creator,keyHolder);

        // *返回user的id
        long userId = keyHolder.getKey().longValue();
        return userId;
    }

    /**
     * day06-17 : 添加 用户_角色_关系 数据，往sys_user_role表
     * @param userId
     * @param roleId
     */
    @Override
    public void addUserRole(Long userId, Long roleId) {
        jdbcTemplate.update("insert into sys_user_role values(?,?)",userId,roleId);
    }


    /*day06-18: 删除。1.sys_user_role关系、2.sys_user信息
    * */
    @Override
    public void deleteUserRoleByUserId(Long userId) {
        jdbcTemplate.update("delete from sys_user_role where userId=?",userId);
    }
    @Override
    public void deleteUserByUserId(Long userId) {
        jdbcTemplate.update("delete from sys_user where id=?",userId);
    }


    /**
     * 验证 账号密码是否正确，查完把查到的user回传service层(service验证 user为null没查到，user不为null查到了)
     * @param user
     * @return
     */
    @Override
    public User loginCheck(User user) throws EmptyResultDataAccessException {
        User userResult = jdbcTemplate.queryForObject("select * from sys_user where username=? and password=?", new BeanPropertyRowMapper<User>(User.class), user.getUsername(), user.getPassword());
        return userResult;
    }
}
